package codepulse.blogmoon.cn.common.dubbo;

import codepulse.blogmoon.cn.common.context.Context;
import codepulse.blogmoon.cn.common.exception.BizException;
import codepulse.blogmoon.cn.common.utils.GsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;

@Slf4j
@Activate(group = {CommonConstants.PROVIDER})
public class DubboProviderContextFilter implements Filter, Filter.Listener {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            String contextJson = RpcContext.getServiceContext().getAttachment("context");
            Context itemContext = GsonUtil.fromJsonObject(contextJson, Context.class);
            if (null != itemContext) {
                Context.get().setBizAcctId(itemContext.getBizAcctId());
                Context.get().setTeamId(itemContext.getTeamId());
            }
            return invoker.invoke(invocation);
        } catch (BizException e) {
            throw e;
        }
    }

    @Override
    public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {

    }

    @Override
    public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {

    }
}
